<?php

namespace app\api\controller\User;

use think\Controller;
use think\Request;

class Auth extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->UserModel = model('User.User');
    }

    //登录授权
    public function login()
    {
        $code = $this->request->param('code');
        $code2session = $this->code2session($code);
        $openid = isset($code2session['openid']) ? $code2session['openid'] : '';
        // halt($openid);
        if (empty($openid)) {
            $this->error('获取凭证失败');
        }

        $User = model('User.User')->where(['openid' => $openid])->find();

        if (!$User) {
            $this->error('您未绑定账号，请先绑定', '/pages/bind/bind');
        }

        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar_cdn' => $User['avatar_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $User['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'cover_cdn' => $User['cover_cdn'],
            'region_text' => $User['region_text']
        ];
        $this->success('登录成功', null, $data);
    }

    //小程序授权绑定接口
    public function bind()
    {
        $code = $this->request->param('code');
        $email = $this->request->param('email');
        $password = $this->request->param('password');

        if (!$code) {
            $this->error('授权失败');
        }

        $code2session = $this->code2session($code);
        $openid = isset($code2session['openid']) ? $code2session['openid'] : '';
        if (empty($openid)) {
            $this->error('获取凭证失败');
        }
        $User = model('User.User')->where(['email' => $email])->find();

        if ($User) {
            $password = md5($password . $User['salt']);

            if ($password != $User['password']) {
                $this->error('密码错误');
            }

            $data = [
                'id' => $User['id'],
                'openid' => $openid
            ];

            $result = model('User.User')->isUpdate(true)->save($data);

            if ($result === FALSE) {
                $this->error('绑定失败');
            } else {
                $UserData = [
                    'id' => $User['id'],
                    'email' => $User['email'],
                    'nickname' => $User['nickname'],
                    'avatar_cdn' => $User['avatar_cdn'],
                    'sex' => $User['sex'],
                    'sex_text' => $User['sex_text'],
                    'province' => $User['province'],
                    'city' => $User['city'],
                    'district' => $User['district'],
                    'createtime' => $User['createtime'],
                    'content' => $User['content'],
                    'point' => $User['point'],
                    'vip' => $User['vip'],
                    'auth' => $User['auth'],
                    'cover_cdn' => $User['cover_cdn'],
                    'region_text' => $User['region_text']
                ];

                $this->success('绑定成功', null, $UserData);
            }
        } else {
            // 密码盐
            $salt = build_ranstr();

            $password = md5($password . $salt);

            $point = model('Config')->where(['key' => 'RegisterPoint'])->value('value');


            $data = [
                'email' => $email,
                'password' => $password,
                'salt' => $salt,
                'openid' => $openid,
                'point' => $point,
                'vip' => 1,
                'auth' => 0,
                'sex' => 0
            ];

            $result = $this->UserModel->validate('common/User/User.vue')->save($data);

            if ($result === FALSE) {
                $this->error($this->UserModel->getError());
            } else {
                $User = $this->UserModel->find($this->UserModel->id);

                $UserData = [
                    'id' => $User['id'],
                    'email' => $User['email'],
                    'nickname' => $User['nickname'],
                    'avatar_cdn' => $User['avatar_cdn'],
                    'sex' => $User['sex'],
                    'sex_text' => $User['sex_text'],
                    'province' => $User['province'],
                    'city' => $User['city'],
                    'district' => $User['district'],
                    'createtime' => $User['createtime'],
                    'content' => $User['content'],
                    'point' => $User['point'],
                    'vip' => $User['vip'],
                    'auth' => $User['auth'],
                    'cover_cdn' => $User['cover_cdn'],
                    'region_text' => $User['region_text']
                ];

                $this->success('绑定成功', null, $UserData);
            }
        }
    }

    //封装一个生成小程序code函数
    public function code2session($code)
    {
        //confit.php => 配置一个appid和密钥
        $appid = 'wxcc6288403be9f92e';
        $secret = 'e3337fd81209e11f6127a5caed480d9b';

        $ApiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";

        $result = $this->https_request($ApiUrl);

        $result = json_decode($result, true);

        if (!$result) {
            return false;
        } else {
            return $result;
        }
    }

    //微信授权请求方法
    private function https_request($url, $data = null)
    {
        if (function_exists('curl_init')) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        } else {
            return false;
        }
    }

    //基本资料修改
    public function profile()
    {
        $userid = $this->request->param('userid');
        $params = $this->request->param();
        $user = $this->UserModel->find($userid);

        if (!$user) {
            $this->error('用户不存在，请重新绑定账号。');
        }

        //封装数据
        $data = [
            'id' => $userid,
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'content' => $params['content']
        ];

        //获取更改后的地区数据
        if (!empty($params['code'])) {
            $parentpath = model('Region')->where(['code' => $params['code']])->value('parentpath');

            if (!$parentpath) {
                $this->error('所选地区不存在');
            }

            // [$province, $city, $district] = explode(',', $parentpath);
            $array = explode(',', $parentpath);
            $province = $array[0];
            $city = $array[1];
            $district = $array[2];

            if ($province) {
                $data['province'] = $province;
            }

            if ($city) {
                $data['city'] = $city;
            }

            if ($district) {
                $data['district'] = $district;
            }
        }

        //图片上传数据
        if (isset($_FILES['cover']) && $_FILES['cover']['size']) {
            $cover = upload('cover');
            if ($cover['code'] == 0) {
                $this->error($cover['msg']);
            }
            $data['cover'] = $cover['data'];
        }

        $result = $this->UserModel->isUpdate(true)->save($data);

        if ($result === FALSE) {
            if (isset($_FILES['cover']) && $_FILES['cover']['size']) {
                @is_file('.' . $data['cover']) && @unlink('.' . $data['cover']);
            }
            $this->error('修改失败');
        } else {
            if (isset($_FILES['cover']) && $_FILES['cover']['size']) {
                @is_file('.' . $user['cover']) && @unlink('.' . $user['cover']);
            }
            $User = $this->UserModel->find($userid);

            $UserData = [
                'id' => $User['id'],
                'email' => $User['email'],
                'nickname' => $User['nickname'],
                'avatar_cdn' => $User['avatar_cdn'],
                'sex' => $User['sex'],
                'sex_text' => $User['sex_text'],
                'province' => $User['province'],
                'city' => $User['city'],
                'district' => $User['district'],
                'createtime' => $User['createtime'],
                'content' => $User['content'],
                'point' => $User['point'],
                'vip' => $User['vip'],
                'auth' => $User['auth'],
                'cover_cdn' => $User['cover_cdn'],
                'region_text' => $User['region_text']
            ];

            $this->success('修改成功', null, $UserData);
        }
    }
}
